package com.xinjie.www.dao.thumb;

import com.xinjie.www.dao.BaseDao;
import com.xinjie.www.po.Thumb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ThumbDaoImpl implements ThumbDao {
    //进行点赞
    @Override
    public int doThumb(Connection connection, int postId, int userId, String time) throws SQLException {
        PreparedStatement pstm = null;
        Object[] params1 = {postId, userId, time};
        String sql1 = "insert into thumb (post_id,user_id,time) values(?,?,?)";
        int excute1 = BaseDao.excute(connection, pstm, sql1, params1);
        if (excute1 > 0) {
            String sql2 = "update post set thumb=thumb+1 where post_id=?";
            Object[] params2 = {postId};
            int excute2 = BaseDao.excute(connection, pstm, sql2, params2);
        }
        BaseDao.closeResource(null, pstm, null);
        return excute1;
    }

    //获取点赞
    @Override
    public List<Thumb> getThumb(Connection connection, int userId) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<Thumb> thumbs = new ArrayList<>();
        Object[] params = {userId};
        String sql = "select * from thumb where user_id = ?";
        rs = BaseDao.excute(connection, pstm, rs, sql, params);
        while (rs.next()) {
            Thumb thumb = new Thumb();
            thumb.setThumbId(rs.getInt("thumb_id"));
            thumb.setPostId(rs.getInt("post_id"));
            thumb.setUserId(rs.getInt("user_id"));
            thumb.setTime(rs.getString("time"));
            thumbs.add(thumb);
        }
        BaseDao.closeResource(null, pstm, rs);
        return thumbs;
    }

    //取消点赞
    @Override
    public int cancelThumb(Connection connection, int thumbId, int postId) throws SQLException {
        PreparedStatement pstm = null;
        Object[] params1 = {thumbId};
        String sql1 = "delete from thumb where thumb_id=?";
        int excute1 = BaseDao.excute(connection, pstm, sql1, params1);
        if (excute1 > 0) {
            String sql2 = "update post set thumb = thumb-1 where post_id = ? ";
            Object[] params2 = {postId};
            int excute2 = BaseDao.excute(connection, pstm, sql2, params2);
        }
        BaseDao.closeResource(null, pstm, null);
        return excute1;
    }
}
